package com.hxqh.bo.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hxqh.bo.bean.FpsFundInfo;

/**
 * A data access object (DAO) providing persistence and search support for
 * FpsFundInfo entities. Transaction control of the save(), update() and
 * delete() operations can directly support Spring container-managed
 * transactions or they can be augmented to handle user-managed Spring
 * transactions. Each of these methods provides additional information for how
 * to configure it for the desired type of transaction control.
 * 
 * @see com.hxqh.bo.bean.FpsFundInfo
 * @author MyEclipse Persistence Tools
 */

public class FpsFundInfoDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(FpsFundInfoDAO.class);
	// property constants
	public static final String POLICY_ID = "policyId";
	public static final String FUND_FLOAT = "fundFloat";
	public static final String FUTURES_CODE = "futuresCode";
	public static final String POLICY_ORDER_NO = "policyOrderNo";
	public static final String OPEN_PRICE = "openPrice";
	public static final String CLOSE_PRICE = "closePrice";
	public static final String SELL = "sell";
	public static final String DIRECTION = "direction";
	public static final String POLICY_NAME = "policyName";

	protected void initDao() {
		// do nothing
	}
	
	public List getTradeDate(final String appendSql) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String sql = "select distinct TRADE_DATE" +
						" from fps_fund_info " + appendSql + 
						" order by TRADE_DATE asc";
				log.info(sql);
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("TRADE_DATE", Hibernate.TIMESTAMP);
				return q.list();
			}
		});
	}
	
	public List findFundInfoLastIntervalDay(final String appendSql) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String sql = "select POLICY_ID,TRADE_DATE,FUND_FLOAT " +
						" from fps_fund_info " + appendSql +
						" order by TRADE_DATE asc";
				log.info(sql);
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("POLICY_ID", Hibernate.INTEGER);
				q.addScalar("TRADE_DATE", Hibernate.TIMESTAMP);
				q.addScalar("FUND_FLOAT", Hibernate.DOUBLE);
				return q.list();
			}
		});
	}
	
	public Double getLastFundFloatByPolicyId(final Integer policyId) {
		Double fund = (Double) getHibernateTemplate().execute(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session arg0)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						String sql = "select fund_float from fps_fund_info where policy_fund_id = " +
								"(select max(b.policy_fund_id) from fps_fund_info b where b.policy_id=" + policyId +")";
						SQLQuery q = arg0.createSQLQuery(sql);
						q.addScalar("fund_float", Hibernate.DOUBLE);
						return q.uniqueResult();
					}
				});

		return fund!=null?fund:new Double(0);
	}

	public void save(FpsFundInfo transientInstance) {
		log.debug("saving FpsFundInfo instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(FpsFundInfo persistentInstance) {
		log.debug("deleting FpsFundInfo instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public FpsFundInfo findById(java.lang.Long id) {
		log.debug("getting FpsFundInfo instance with id: " + id);
		try {
			FpsFundInfo instance = (FpsFundInfo) getHibernateTemplate().get(
					"com.hxqh.bo.bean.FpsFundInfo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(FpsFundInfo instance) {
		log.debug("finding FpsFundInfo instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding FpsFundInfo instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from FpsFundInfo as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByPolicyId(Object policyId) {
		return findByProperty(POLICY_ID, policyId);
	}

	public List findByFundFloat(Object fundFloat) {
		return findByProperty(FUND_FLOAT, fundFloat);
	}

	public List findByFuturesCode(Object futuresCode) {
		return findByProperty(FUTURES_CODE, futuresCode);
	}

	public List findByPolicyOrderNo(Object policyOrderNo) {
		return findByProperty(POLICY_ORDER_NO, policyOrderNo);
	}

	public List findByOpenPrice(Object openPrice) {
		return findByProperty(OPEN_PRICE, openPrice);
	}

	public List findByClosePrice(Object closePrice) {
		return findByProperty(CLOSE_PRICE, closePrice);
	}

	public List findBySell(Object sell) {
		return findByProperty(SELL, sell);
	}

	public List findByDirection(Object direction) {
		return findByProperty(DIRECTION, direction);
	}

	public List findByPolicyName(Object policyName) {
		return findByProperty(POLICY_NAME, policyName);
	}

	public List findAll() {
		log.debug("finding all FpsFundInfo instances");
		try {
			String queryString = "from FpsFundInfo";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findTop30Desc() {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
	
			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				String sql = "select a.POLICY_NAME,a.FUTURES_CODE,a.SELL,a.TRADE_DATE," +
						"b.ALL_TRADE_NUM,a.OPEN_PRICE,a.CLOSE_PRICE " +
						"from fps_fund_info a, fps_policy_statistics_info b where a.POLICY_ID=b.POLICY_ID " +
						"order by a.TRADE_DATE desc limit 30";
				log.info(sql);
				SQLQuery q = arg0.createSQLQuery(sql);
				q.addScalar("POLICY_NAME",Hibernate.STRING);
				q.addScalar("FUTURES_CODE",Hibernate.STRING);
				q.addScalar("SELL",Hibernate.INTEGER);
				q.addScalar("TRADE_DATE",Hibernate.TIMESTAMP);
				q.addScalar("ALL_TRADE_NUM",Hibernate.INTEGER);
				q.addScalar("OPEN_PRICE",Hibernate.DOUBLE);
				q.addScalar("CLOSE_PRICE",Hibernate.DOUBLE);
				return q.list();
			}
		});
	}
	
	public FpsFundInfo merge(FpsFundInfo detachedInstance) {
		log.debug("merging FpsFundInfo instance");
		try {
			FpsFundInfo result = (FpsFundInfo) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(FpsFundInfo instance) {
		log.debug("attaching dirty FpsFundInfo instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(FpsFundInfo instance) {
		log.debug("attaching clean FpsFundInfo instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static FpsFundInfoDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (FpsFundInfoDAO) ctx.getBean("FpsFundInfoDAO");
	}
}